# -*- coding: utf-8 -*-
import sys
sys.path.append('../..')
from common.config import *
from db.mysql import MysqlClient
from itertools import product
import requests,json
from common.helper import Helper

class Spider(object):
    def __init__(self):
        self.mysql = MysqlClient()
        self.name = "人保寿险无忧人生2019重大疾病保险"

    # 生成产品数据
    def genProductInfo(self):
        plan = {
            "planA": {
                # 年龄段
                "year": [str(i) for i in range(0, 41)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["终身"],
                # 缴费间隔
                "interval": ["0", "5", "10", "15", "20", "29", "30"],
                # 保险金额
                "money": ["50000", "100000", "200000", "400000", "500000", "600000"],
            },
            "planB": {
                # 年龄段
                "year": [str(i) for i in range(41, 46)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["终身"],
                # 缴费间隔
                "interval": ["0", "5", "10", "15", "20"],
                # 保险金额
                "money": ["50000", "100000", "200000", "400000"],
            },
            "planC": {
                # 年龄段
                "year": [str(i) for i in range(46, 51)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["终身"],
                # 缴费间隔
                "interval": ["0", "5", "10", "15", "20"],
                # 保险金额
                "money": ["50000", "100000", "200000", "300000"],
            },
            "planD": {
                # 年龄段
                "year": [str(i) for i in range(51, 56)],
                # 性别
                "gender": ["M", "F"],
                # 保障期限
                "expire": ["终身"],
                # 缴费间隔
                "interval": ["0", "5", "10", "15"],
                # 保险金额
                "money": ["30000", "50000", "80000", "100000"]
            }
        }
        for k in plan:
            for v in product(plan[k]["year"], plan[k]["gender"], plan[k]["expire"], plan[k]["interval"],
                             plan[k]["money"]):
                if v[3] == "0":
                    payType = "一次交清"
                else:
                    payType = "年交"
                self.mysql.cursor.execute(domain[self.name]["insert_sql"].format(
                    v[0], v[1], v[2], v[3], v[4], payType
                ))
                self.mysql._conn.commit()
                print(
                    domain[self.name]["insert_sql"].format(
                        v[0], v[1], v[2], v[3], v[4], payType
                    )
                )

    # 执行爬虫
    def requestJson(self, dt=None):

        data = {"addProductCode": "", "addperAmount": 0, "age": dt["year"], "combCode": "WYRSZDJB", "endyear": 0,
                "grossPremium": 0, "insuYear": 106, "insuYearFlag": "Y", "payEndYear": dt["interval"], "payWay": "1",
                "payperiod": "", "paytype": "", "payyear": 0, "perAmount": dt["money"], "productCode": "70563", "sex": dt["gender"]}

        payload = json.dumps( data )

        r = requests.post( url = domain[self.name]["url"],headers=domain[self.name]["header"],data=payload)

        if r.status_code == 200:

            price = Helper.decimalParse( r.json()["grossPremium"])

            data = {
                "name":self.name,
                "id":dt["id"],
                "price":price
            }
            self.mysql.updatePrice( data )
        else:
            data = {
                "name":self.name,
                "id":dt["id"],
                "state":3
            }
            self.mysql.updateTask( data )
            print("\n/*更新产品价格数据失败:%d*/"%dt["id"])

    def main(self):

        while True:

            # 随机领取一条数据
            dt = self.mysql.randTask(self.name)

            if not dt:

                print("产品价格抓取完成~~~")

                return

                # 任务执行状态
            data = {
                "name": self.name,
                "id": dt["id"],
                "state": 1
            }
            self.mysql.updateTask(data)

            self.requestJson( dt )
